package com.nopay.dxdwphone.ui.ativity;

import android.os.Bundle;
import android.widget.LinearLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseActivity;
import com.nopay.dxdwphone.bean.request.GetCallTaskUnCallRequest;
import com.nopay.dxdwphone.bean.request.SaveCallTaskRequest;
import com.nopay.dxdwphone.bean.response.GetCallTaskCallResponse;
import com.nopay.dxdwphone.bean.response.GetCallTaskGroupResponse;
import com.nopay.dxdwphone.bean.response.SaveCallTaskResponse;
import com.nopay.dxdwphone.dialog.DialogDialedStatus;
import com.nopay.dxdwphone.dialog.DialogRecallLoading;
import com.nopay.dxdwphone.ui.fragment.task.DialedFragment;
import com.nopay.dxdwphone.ui.fragment.task.ToBeDialedFragment;

import java.util.ArrayList;
import java.util.List;

import com.nopay.dxdwphone.CallGroupEnum;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.ActivityCallTaskDetailBinding;

import com.nopay.dxdwphone.ui.adapter.MyFragmentAdapter;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CallTaskDetailActivity extends BaseActivity<ActivityCallTaskDetailBinding> {

    private static final String[] TAB_LIST = {"待拨打", "已拨打"};

    private ToBeDialedFragment toBeDialedFragment;
    private DialedFragment dialedFragment;

    public GetCallTaskGroupResponse.Data mCallTask;

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(CallTaskDetailActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        mCallTask = (GetCallTaskGroupResponse.Data) getIntent().getSerializableExtra(Constants._CALL_TASK_GROUP);
        if(mCallTask == null) return;
        binding.tvTitle.setText(mCallTask.getTaskName());

        toBeDialedFragment = new ToBeDialedFragment();
        dialedFragment = new DialedFragment();
        List<Fragment> mFragmentList = new ArrayList<>();
        mFragmentList.add(toBeDialedFragment);
        mFragmentList.add(dialedFragment);

        List<String> mTitleList = new ArrayList<>();
        mTitleList.add(TAB_LIST[0]);
        mTitleList.add(TAB_LIST[1]);

        binding.tabCallStatus.setupWithViewPager(binding.vpCallStatus);
        binding.vpCallStatus.setOffscreenPageLimit(2);
        MyFragmentAdapter fragmentPageAdapter = new MyFragmentAdapter(mFragmentList, mTitleList, getSupportFragmentManager());
        binding.vpCallStatus.setAdapter(fragmentPageAdapter);

        LinearLayout linearLayout = (LinearLayout) binding.tabCallStatus.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(CallTaskDetailActivity.this, R.drawable.shape_call_task_tab_divider_line));
        linearLayout.setDividerPadding(45);

        initCallCount();
    }

    public void refreshTabText(int tabIndex, int count) {
        binding.tabCallStatus.getTabAt(tabIndex).setText(TAB_LIST[tabIndex] + "（" + count + "）");
    }

    public void initCallCount() {
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        Integer taskId = mCallTask.getId();

        GetCallTaskUnCallRequest request = new GetCallTaskUnCallRequest();
        request.setPhone(phone);
        request.setTaskId(taskId);
        request.setPageNum(1);
        request.setPageSize(1);
        RequestBody body = getRequestBody(request);

        api.doGetCallLogList(body).enqueue(new Callback<GetCallTaskCallResponse>() {
            @Override
            public void onResponse(Call<GetCallTaskCallResponse> call, Response<GetCallTaskCallResponse> response) {
                int count = 0;
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        count = response.body().getTotal();
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
                refreshTabText(1, count);
            }

            @Override
            public void onFailure(Call<GetCallTaskCallResponse> call, Throwable t) {
                refreshTabText(1, 0);
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });

        api.doGetCallTaskUnCall(body).enqueue(new Callback<GetCallTaskCallResponse>() {
            @Override
            public void onResponse(Call<GetCallTaskCallResponse> call, Response<GetCallTaskCallResponse> response) {
                int count = 0;
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        count = response.body().getTotal();
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
                refreshTabText(0, count);
            }

            @Override
            public void onFailure(Call<GetCallTaskCallResponse> call, Throwable t) {
                refreshTabText(0, 0);
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

    private DialogRecallLoading mRecallLoading;

    /**
     * 创建重拨任务
     */
    public void createTaskForRecall() {
        new DialogDialedStatus(CallTaskDetailActivity.this).setOnDialedStatusConfirmListener((statusNo, statusYes) -> {
            if(statusNo || statusYes) {
                mRecallLoading = new DialogRecallLoading(CallTaskDetailActivity.this);
                mRecallLoading.show();
                queryTaskAndSave(statusNo, statusYes, 1);
            } else {
                // 未选择
                ToastUtils.showShort("未选择重拨任务类型");
            }
        }).show();
    }

    public void queryTaskAndSave(boolean statusNo, boolean statusYes, int pageNum) {
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        GetCallTaskUnCallRequest request = new GetCallTaskUnCallRequest();
        request.setPhone(phone);
        request.setTaskId(mCallTask.getId());
        request.setPageNum(pageNum);
        request.setPageSize(1000);
        RequestBody body = getRequestBody(request);

        api.doGetCallLogList(body).enqueue(new Callback<GetCallTaskCallResponse>() {
            @Override
            public void onResponse(Call<GetCallTaskCallResponse> call, Response<GetCallTaskCallResponse> response) {
//                int count = 0;
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        if(response.body().getTotal() < 0) {
                            if(mRecallLoading != null) {
                                mRecallLoading.dismiss();
                                mRecallLoading = null;
                            }
                            ToastUtils.showShort("暂无已拨号数据");
                            return;
                        }

                        int total = response.body().getTotal();
                        int progress = pageNum * 1000 * 100 / total;
                        if(progress > 100) progress = 100;

                        List<GetCallTaskCallResponse.Data>  callInfoList = response.body().getRows();
                        List<SaveCallTaskRequest.Data> taskData = new ArrayList<>();
                        for (int i = 0; i < callInfoList.size(); i++) {
                            GetCallTaskCallResponse.Data callInfo = callInfoList.get(i);
                            if((callInfo.getStatus() == 2 && statusNo) || (callInfo.getStatus() == 1 && statusYes)) {
                                SaveCallTaskRequest.Data data = new SaveCallTaskRequest.Data();
                                data.setCompany(callInfo.getCompany());
                                data.setName(callInfo.getName());
                                data.setPhone(callInfo.getCalledNumber());
                                taskData.add(data);
                            }
                        }

                        if(taskData.size() == 0) {
                            if(mRecallLoading != null) {
                                mRecallLoading.dismiss();
                                mRecallLoading = null;
                            }
                            ToastUtils.showShort("无拨号数据");
                            return;
                        }

                        SaveCallTaskRequest bean = new SaveCallTaskRequest();
                        bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
                        bean.setImportGroup(CallGroupEnum.IMPORT_RECALL);
                        bean.setPersonnelInfoSaveReqVOs(taskData);

                        RequestBody body = getRequestBody(bean);
                        int finalProgress = progress;
                        api.doSaveCallTaskToGroup(body).enqueue(new Callback<SaveCallTaskResponse>() {
                            @Override
                            public void onResponse(Call<SaveCallTaskResponse> call, Response<SaveCallTaskResponse> response) {
                                if(mRecallLoading != null) mRecallLoading.setLoadingText("正在创建重拨任务.... " + finalProgress + "%");
                                if (response.body() != null) {
                                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
//                                        ToastUtils.showShort("添加到重拨任务成功");
                                    } else {
//                                        ToastUtils.showShort(response.body().getMsg());
                                    }
                                }
                                if(finalProgress >= 100) {
                                    if(mRecallLoading != null) {
                                        mRecallLoading.dismiss();
                                        mRecallLoading = null;
                                    }
                                    ToastUtils.showShort("添加到重拨任务成功");
                                } else {
                                    queryTaskAndSave(statusNo, statusYes, pageNum + 1);
                                }
                            }

                            @Override
                            public void onFailure(Call<SaveCallTaskResponse> call, Throwable t) {
//                                ToastUtils.showShort(CallTaskDetailActivity.this.getResources().getString(R.string.call_api_error));
                                if(mRecallLoading != null) mRecallLoading.setLoadingText("正在创建重拨任务.... " + finalProgress + "%");
                                if(finalProgress >= 100) {
                                    if(mRecallLoading != null) {
                                        mRecallLoading.dismiss();
                                        mRecallLoading = null;
                                    }
                                    ToastUtils.showShort("添加到重拨任务成功");
                                } else {
                                    queryTaskAndSave(statusNo, statusYes, pageNum + 1);
                                }
                            }
                        });
                    } else {
                        if(mRecallLoading != null) {
                            mRecallLoading.dismiss();
                            mRecallLoading = null;
                        }
                        ToastUtils.showShort("暂无已拨号数据");
                    }
                } else {
                    if(mRecallLoading != null) {
                        mRecallLoading.dismiss();
                        mRecallLoading = null;
                    }
                }
//                refreshTabText(1, count);
            }

            @Override
            public void onFailure(Call<GetCallTaskCallResponse> call, Throwable t) {
//                refreshTabText(1, 0);
                if(mRecallLoading != null) {
                    mRecallLoading.dismiss();
                    mRecallLoading = null;
                }
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

//    public void openMemberPage() {
//        mSwipeBackHelper.forward(RechargeActivity.class);
//    }

    public void openCallSetting() {
        mSwipeBackHelper.forward(CallSettingActivity.class);
    }
}
